package controllers.bluehat;

import java.util.HashMap;
import java.util.List;

import org.hibernate.ejb.criteria.expression.function.CurrentDateFunction;

import play.Logger;
import play.data.validation.Valid;
import play.i18n.Messages;
import utils.json.data.MessageJson;
import models.Focus;
import models.IdeaRequest;
import models.InformationRequest;
import models.User;

public class IdeaRequestController extends BlueHatBaseController {
	
	/**
	 * Renders the form to create new information request about the current focus.
	 */
	public static void form(Long id) {
		Focus focus = Focus.getById(id, null);
		if(!getCurrentUser().equals(focus.owner)) error(); // TODO same code that in FocusController
		
		
		render(focus);
	}
	
	public static void save(Long id, IdeaRequest ideaRequest) {
		Focus focus = Focus.getById(id, null);
		if(!getCurrentUser().equals(focus.owner)) error(); // TODO same code that in FocusController
		ideaRequest.focus = focus;
		
		// Validations TODO add more validations based on dates.
		// Custom validation. Restriction over the dates.
		List<IdeaRequest> open = IdeaRequest.findAllOpen(ideaRequest.start, focus.ideasRequest);
		if(open.size() > 0) {
			validation.addError("Dates", "Ya hay procesos planificados en esa fecha. Verifique que es correcta la seleccion de fechas", new String[]{});
		}
		validation.valid(ideaRequest);
		if(validation.hasErrors()) {
			render("bluehat/ideaRequestController/form.html", focus, ideaRequest);
		} else {
			ideaRequest.save();
		}
		
		FocusController.detail(id);
	}
	
	public static void detail(Long id) {
		IdeaRequest ideaRequest = IdeaRequest.findById(id);
		
		render(ideaRequest);
	}
	
	public static void confirm_delete(Long id) {
		IdeaRequest ideaRequest = IdeaRequest.findById(id); 
		render(ideaRequest);
	}
	
	public static void delete(Long id, Boolean confirm) {
		IdeaRequest ideaRequest = IdeaRequest.findById(id); 
		Long focusId = ideaRequest.focus.id;
		// TODO validation!
		if(confirm != null && confirm) {
			/*Logger.info("Removing a focus! This action will remove all child relations. This action is executed here!");
			for(InformationRequest infoRequest : focus.informationRequest.iter()) {
				Logger.debug("Now removing information units!");
				infoRequest.informations.delete();
			}
			Logger.debug("Now removing all information requests!");
			focus.informationRequest.delete();*/
			Logger.debug("Removing idea request with it: %d", id);
			ideaRequest.delete();
		}
		
		FocusController.detail(focusId);
	}
}
